#include "my_spi.h"

static const char *TAG = "my_spi.c";

esp_err_t my_spi_rw(uint8_t *txbuf, uint8_t *rxbuf, uint8_t txlen, uint8_t rxlen )
{
	if (txlen > 64) {
		ESP_LOGE(TAG, "ESP8266 only support transmit 64bytes");
		return ESP_FAIL;
	}

	if (rxlen > 64) {
		ESP_LOGE(TAG, "ESP8266 only support transmit 64bytes");
		return ESP_FAIL;
	}

	spi_trans_t trans = {0};
	trans.mosi = (uint32_t*)txbuf;
	trans.miso = (uint32_t*)rxbuf;
	trans.bits.val = 0;
	trans.bits.mosi = txlen * 8;
	trans.bits.miso = rxlen * 8;
	spi_trans(HSPI_HOST, &trans);
	return ESP_OK;
}

esp_err_t my_spi_write(uint8_t *txbuf, uint8_t txlen)
{
	if (txlen > 64) {
		ESP_LOGE(TAG, "ESP8266 only support transmit 64bytes");
		return ESP_FAIL;
	}

	spi_trans_t trans = {0};
	trans.mosi = (uint32_t*)txbuf;
	trans.bits.val = 0;
	trans.bits.mosi = txlen * 8;
	spi_trans(HSPI_HOST, &trans);
	return ESP_OK;
}

esp_err_t my_spi_read(uint8_t *rxbuf, uint8_t rxlen)
{
	if (rxlen > 64) {
		ESP_LOGE(TAG, "ESP8266 only support transmit 64bytes");
		return ESP_FAIL;
	}

	spi_trans_t trans = {0};
	trans.miso = (uint32_t*)rxbuf;
	trans.bits.val = 0;
	trans.bits.miso = rxlen * 8;
	spi_trans(HSPI_HOST, &trans);
	return ESP_OK;
}

void my_spi_init(spi_event_callback_t cb)
{    
	ESP_LOGI(TAG, "init hspi");
	spi_config_t spi_config;
	// Load default interface parameters
	// CS_EN:1, MISO_EN:1, MOSI_EN:1, BYTE_TX_ORDER:1, BYTE_TX_ORDER:1, BIT_RX_ORDER:0, BIT_TX_ORDER:0, CPHA:0, CPOL:0
	spi_config.interface.val = SPI_DEFAULT_INTERFACE;
	// Load default interrupt enable
	// TRANS_DONE: true, WRITE_STATUS: false, READ_STATUS: false, WRITE_BUFFER: false, READ_BUFFER: false
	spi_config.intr_enable.val = SPI_MASTER_DEFAULT_INTR_ENABLE;
	// CPOL: 1, CPHA: 1
	spi_config.interface.cpol = 1;
	spi_config.interface.cpha = 1;
	// Set SPI to master mode
	// 8266 Only support half-duplex
	spi_config.mode = SPI_MASTER_MODE;
	// Set the SPI clock frequency division factor
	spi_config.clk_div = SPI_10MHz_DIV;
	// Register SPI event callback function
	spi_config.event_cb = cb;
	spi_init(HSPI_HOST, &spi_config);
}

